"use client"
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';
import { deleteQuestionBankUsingPost, listQuestionBankByPageUsingPost } from '@/api/questionBankController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Space, Typography, Upload } from 'antd';
import { uploadFileUsingPost } from '@/api/fileController';
import request from '@/libs/request';
import React, { useRef, useState } from 'react';

/**
 * 题库管理页面
 *
 * @constructor
 */
const QuestionBankAdminPage: React.FC = () => {
    // 是否显示新建窗口
    const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
    // 是否显示更新窗口
    const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    // 当前题库点击的数据
    const [currentRow, setCurrentRow] = useState<API.QuestionBank>();

    /**
     * 删除节点
     *
     * @param row
     */
    const handleDelete = async (row: API.QuestionBank) => {
        const hide = message.loading('正在删除');
        if (!row) return true;
        try {
            await deleteQuestionBankUsingPost({
                id: row.id as any,
            });
            hide();
            message.success('删除成功');
            actionRef?.current?.reload();
            return true;
        } catch (error: any) {
            hide();
            message.error('删除失败，' + error.message);
            return false;
        }
    };

    /**
     * 表格列配置
     */
    const columns: ProColumns<API.QuestionBank>[] = [
        {
            title: "id",
            dataIndex: "id",
            valueType: "text",
            hideInForm: true,
        },
        {
            title: "标题",
            dataIndex: "title",
            valueType: "text",
        },
        {
            title: "描述",
            dataIndex: "description",
            valueType: "text",
        },
        {
            title: "图片",
            dataIndex: "picture",
            valueType: "image",
            fieldProps: {
                width: 64,
            },
            hideInSearch: true,
        },
        {
            title: "创建时间",
            sorter: true,
            dataIndex: "createTime",
            valueType: "dateTime",
            hideInSearch: true,
            hideInForm: true,
        },
        {
            title: "编辑时间",
            sorter: true,
            dataIndex: "editTime",
            valueType: "dateTime",
            hideInSearch: true,
            hideInForm: true,
        },
        {
            title: "更新时间",
            sorter: true,
            dataIndex: "updateTime",
            valueType: "dateTime",
            hideInSearch: true,
            hideInForm: true,
        },
        {
            title: "操作",
            dataIndex: "option",
            valueType: "option",
            render: (_, record) => (
                <Space size="middle">
                    <Typography.Link
                        onClick={() => {
                            setCurrentRow(record);
                            setUpdateModalVisible(true);
                        }}
                    >
                        修改
                    </Typography.Link>
                    <Typography.Link type="danger" onClick={() => handleDelete(record)}>
                        删除
                    </Typography.Link>
                </Space>
            ),
        },
    ];

    return (
        <div id="questionBank">
            <PageContainer >
                <ProTable<API.QuestionBank>
                    headerTitle={'查询表格'}
                    actionRef={actionRef}
                    rowKey="key"
                    search={{
                        labelWidth: 120,
                    }}
                    toolBarRender={() => [
                        <Button
                            type="primary"
                            key="primary"
                            onClick={() => {
                                setCreateModalVisible(true);
                            }}
                        >
                            <PlusOutlined /> 新建
                        </Button>,
                    ]}
                    // 列表数据请求：适配后端分页返回结构
                    request={async (params, sort, filter) => {
                        const sortField = Object.keys(sort)?.[0];
                        const sortOrder = sort?.[sortField] ?? undefined;

                        const { data, code } = (await listQuestionBankByPageUsingPost({
                            ...params,
                            sortField,
                            sortOrder,
                            ...filter,
                        } as API.QuestionBankQueryRequest)) as any;

                        return {
                            success: code === 0,
                            data: (data?.records || []) as any,
                            total: Number((data as any)?.total) || 0,
                        } as any;
                    }}
                    columns={columns}
                    pagination={{
                        // 使用 ProTable 内部的分页管理
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: ['10', '20', '50', '100'],
                        showTotal: (total, range) =>
                            `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                    }}
                />
                <CreateModal
                    visible={createModalVisible}
                    columns={columns}
                    onSubmit={() => {
                        setCreateModalVisible(false);
                        actionRef.current?.reload();
                    }}
                    onCancel={() => {
                        setCreateModalVisible(false);
                    }}
                />
                <UpdateModal
                    visible={updateModalVisible}
                    columns={columns}
                    oldData={currentRow}
                    onSubmit={() => {
                        setUpdateModalVisible(false);
                        setCurrentRow(undefined);
                        actionRef.current?.reload();
                    }}
                    onCancel={() => {
                        setUpdateModalVisible(false);
                    }}
                />
            </PageContainer>
        </div>

    );
};
export default QuestionBankAdminPage;
